const fs = require('fs')
const path = require('path')

/**
 * 保存 gresource.xml 文件
 * @param {string} lowerName
 */
function saveGResource(lowerName) {
    const type = lowerName.split('_')[0]
    const gresourcePath = path.join(__dirname, '../src', 'index.gresource.xml')
    const gresourceContent = fs.readFileSync(gresourcePath, 'utf8')
    const files = gresourceContent.match(/<file>(.*)<\/file>/g) || []
    const uiLine = `<file>src/${type}s/${lowerName}.ui</file>`
    let hasChange = false
    if (!files.includes(uiLine)) {
        files.push(uiLine)
        hasChange = true
    }
    const cssLine = `<file>src/${type}s/${lowerName}.css</file>`
    if (!files.includes(cssLine)) {
        files.push(cssLine)
        hasChange = true
    }
    if (hasChange) {
        files.sort((a, b) => a.localeCompare(b))
        const newGresourceContent = `<?xml version="1.0" encoding="UTF-8"?>
<gresources>
    <gresource>\n${files.map(a => '        ' + a).join('\n')}</gresource>
</gresources>
`
        fs.writeFileSync(gresourcePath, newGresourceContent)
    }
}

/**
 * 保存 meson.build 文件
 * @param {string} lowerName
 */
function saveMeson(lowerName) {
    const type = lowerName.split('_')[0]
    const mesonPath = path.join(__dirname, '../', 'meson.build')
    const mesonContent = fs.readFileSync(mesonPath, 'utf8')
    const startStr = `${type}_sources`
    const startIndex = mesonContent.indexOf(startStr)
    let endIndex = -1
    for (let i = startIndex; i < mesonContent.length; i++) {
        if (mesonContent[i] === ')') {
            endIndex = i
            break
        }
    }
    endIndex += 1
    const sourceContent = mesonContent.substring(startIndex, endIndex)
    const sources = sourceContent.match(/'.*?'/g) || []
    const cLine = `'src/${type}s/${lowerName}.c'`
    let hasChange = false
    if (!sources.includes(cLine)) {
        sources.push(cLine)
        hasChange = true
    }
    if (hasChange) {
        sources.sort((a, b) => a.localeCompare(b))
        const newSourceContent = `component_sources = files(
${sources.map(a => '    ' + a).join(',\n')},
)`
        const newMesonContent =
            mesonContent.substring(0, startIndex) + newSourceContent + mesonContent.substring(endIndex)
        fs.writeFileSync(mesonPath, newMesonContent)
    }
}

function saveEntry(lowerName, upperTypeName) {
    const type = lowerName.split('_')[0]
    const upperType = type.toUpperCase()
    const entryPath = path.join(__dirname, '../src', 'windows', 'window_index.c')
    const entryContent = fs.readFileSync(entryPath, 'utf8')
    const lines = entryContent.split('\n')
    const includeLines = lines.filter(line => line.includes(`#include "../${type}s`))
    const includeStartIndex = lines.indexOf(includeLines[0])
    if (!includeLines.includes(line => line.includes(lowerName))) {
        const myIncludeLine = `#include "../${type}s/${lowerName}.h"`
        includeLines.push(myIncludeLine)
        includeLines.sort((a, b) => a.localeCompare(b))
        lines.splice(includeStartIndex, includeLines.length - 1, ...includeLines)
    }
    const typeEnsureLines = lines.filter(line => line.includes(`g_type_ensure(${upperType}`))
    const typeEnsureStartIndex = lines.indexOf(typeEnsureLines[0])
    if (!typeEnsureLines.includes(line => line.includes(upperTypeName))) {
        const myTypeEnsureLine = `    g_type_ensure(${upperTypeName});`
        typeEnsureLines.push(myTypeEnsureLine)
        typeEnsureLines.sort((a, b) => a.localeCompare(b))
        lines.splice(typeEnsureStartIndex, typeEnsureLines.length - 1, ...typeEnsureLines)
    }
    const newEntryContent = lines.join('\n')
    fs.writeFileSync(entryPath, newEntryContent)
}

module.exports = {
    saveGResource,
    saveMeson,
    saveEntry,
}
